<template>

  <div class="public-data">

    <div style="border-bottom:1px solid #ddd;" class="option">
      <div class="option-container adaption">
        <div style="display:none;" class="upload-data" @click="upload" v-if="role">
          <i class="iconfont icon-upload"></i>
          <span>上传数据</span>
        </div>
        <ul class="resource-switch clearfix">
          <li @click="handleResSwitch('注册资源',$event)" class="active"><span>注册资源</span></li>
          <li @click="handleResSwitch('申请资源',$event)"><span>申请资源</span></li>
        </ul>
        <div class="range">
          <span @click="changeSortTime">
            <i class="iconfont" :class="`icon-sort-${sortTime}`"></i> 时间
          </span>
          <span @click="changeRangeType">
            <template v-if="isListView"><i class="iconfont icon-tiling"></i> 平铺</template>
            <template v-else><i class="iconfont icon-menu"></i> 列表</template>
          </span>
        </div>

        <div class="search">
          <input type="text" class="input-search" v-model="searchText" v-on:keyup.enter="query" placeholder="搜索">
          <div class="btn-search" @click="query">
            <i class="iconfont icon-loading icon-spin" v-show="isLoading"></i>
            <i class="iconfont icon-search" v-show="!isLoading"></i>
          </div>
        </div>

        <filter-bread-crumb style="display:none;" class="filter-position" v-if="cities && categories" :selected-admin="selectedAdmin"
          :selected-category="selectedCategory"></filter-bread-crumb>

      </div>
    </div>


    <filter-panel v-if="cities && categories" :cities="cities" :categories="categories" class="filter-panel"></filter-panel>

    <div class="data-list-container" style="padding-top:100px;">

      <div v-if="isEmpty" class="no-data">
        <img src="../../../static/img/no-data.png">
      </div>

      <template v-else>
        <div class="wrapper-body">
          <div v-show="isListView" class="list-view-header" :class="[ isListView ? 'adaption-list' : 'adaption']">
            <div class="name">数据名称</div>
            <div class="data-count">数据量</div>
            <div class="date">上传日期</div>
            <div class="data-option">操作</div>
          </div>

          <g-scrollbar class="data-vertical-scroll" :class="{'with-header': isListView}">
            <div :class="[ isListView ? 'adaption-list' : 'adaption']">

              <div class="datas-content">
                <ul class="data-view">
                  <component v-for="(data,index) in dataList" :currentMenu="currentMenu" :is="view" :dataType="dataType"
                    type="public" :data="data" :index="index" :key="data.uid" :isPrivate="false" v-on:open="open"
                    v-on:remove="remove" v-on:data-preview="preview" v-on:data-store="store" v-on:set-current-menu="setCurrentMenu"></component>
                </ul>

                <div class="add-more-wrapper">
                  <button class="add-more" v-show="hasNext" @click="addMore()" :disabled="isLoading">
                    <span v-show="!isLoading">
                      <i class="iconfont icon-flip-down"></i> 加载更多
                    </span>
                    <span v-show="isLoading">
                      <i class="iconfont icon-loading spin"></i> 加载中…
                    </span>
                  </button>
                </div>
              </div>
            </div>
          </g-scrollbar>
        </div>
      </template>

    </div>


    <transition-group name="fade">
      <div :key="'upload-georeference-container'">
        <upload v-if="openUpload" :toPublic="true"></upload>
        <georeference :uid="dataUid" v-if="openGeoreference" :isPublic="true"></georeference>
      </div>
      <div :key="'public-data-preview'">
        <data-preview :is-private="false" :base-path="basePath" :preview-data="previewData" :dataType="dataType"
          v-on:close-preview="closePreview" v-if="openPreview && previewData"></data-preview>
      </div>

    </transition-group>


  </div>

</template>

<script>
  import TilingWrapper from './tiling-wrapper'
  import ListWrapper from './list-wrapper'
  import DataPreview from 'components/preview/data-preview'
  import FilterPanel from 'components/filter/filter-panel'
  import FilterBreadCrumb from 'components/filter/filter-bread-crumb'
  import GScrollbar from 'components/common/g-scrollbar'
  import Upload from 'components/upload/upload'
  import Georeference from './georeference'
  import {
    baseUrl,
    publicDataCategories
  } from '@/config/config'
  import {
    publicData as publicDataAPI,
    organization as orgAPI,
    bookmark as bookmarkAPI
  } from '@/api'
  import GButton from 'components/common/g-button'
  import Bus from '@/utils/event_bus'
  import newConfig from '@/config/newConfig.js'
  import {tianjing as tianjingAPI} from '@/api';

  const viewTypes = ['map', 'table', 'metadata'];
  const limit = 60;

  export default {

    name: 'group-data',

    components: {
      ListWrapper,
      TilingWrapper,
      DataPreview,
      GScrollbar,
      GButton,
      FilterPanel,
      Upload,
      Georeference,
      FilterBreadCrumb
    },

    data() {
      let cities = (this.$root && this.$root.adminRegion && this.$root.adminRegion.length != 0) ?
        this.$root.adminRegion : null;
      let categories = (this.$root && this.$root.dataCategory && this.$root.dataCategory.length != 0) ?
        this.$root.dataCategory : null;
      const dataType = 'data';
      return {
        dataType,
        page: 0, // 默认请求数据页数
        searchText: '', // 用户输入的搜索关键字
        selectedAdmin: null, // 选中的行政区
        selectedCategory: null, // 选中的数据分类
        dataList: [], // 数据列表
        isLoading: false, // 加载数据列表时的搜索组件是否显示缓冲环
        hasNext: false, // 是否多页数据
        previewData: '', // 当前预览数据信息
        openPreview: false, // 是否打开预览窗口
        currentMenu: '', // 用于控制dataWrapper中打开的菜单
        panelShow: false, // 筛选面板是否打开
        cities: cities,
        categories: categories,

        role: this.$root.geohey.user.role || '', // 用户角色
        dataUid: null,
        openUpload: false,
        openGeoreference: false,

        sortTime: 'desc',
        view: 'tiling-wrapper',
        isEmpty: false,
        basePath: '/data/group-data',

        queryParams: {
          type: 'resourceReg',
          ownerType: '2'
        },
        groupId: null
      }
    },

    beforeRouteEnter(to, from, next) {
      next(vm => {
        Bus.$emit('on-submenu-change', '群组资源');
      })
    },

    beforeRouteLeave(to, from, next) {
      this.closePreview();
      next();
    },
    mounted() {

      Bus.$on('filter-panel-change', (params) => {
        this.selectedAdmin = params.admin;
        this.selectedCategory = params.category;
        if (this.selectedAdmin || this.selectedCategory || this.searchText) {
          this.getData(0, false, this.rangeTime);
        }
      });

      Bus.$on('filter-bread-crumb-clear-filter', () => {
        this.searchText = null;
        this.selectedAdmin = null;
        this.selectedCategory = null;
        this.getData(0, false, this.rangeTime);
      });

      Bus.$on('filter-bread-crumb-remove-filter', (filter) => {
        if (filter === 'admin') {
          this.selectedAdmin = null;
        }

        if (filter === 'category') {
          this.selectedCategory = null;
        }
        this.getData(0, false, this.rangeTime);
      });

      Bus.$on('filter-panel-unselect-admin', () => {
        this.selectedAdmin = null;
        this.getData(0, false, this.rangeTime);
      });

      Bus.$on('filter-panel-unselect-category', () => {
        this.selectedCategory = null;
        this.getData(0, false, this.rangeTime);
      });

      Bus.$on('filter-bread-crumb-toggle-panel', () => {
        this.panelShow = !this.panelShow;
      });

      this.$emit('on-view-load');

      //this.$nextTick(function(){
      //});
      Bus.$on('change-group-id', (groupId) => {
        this.groupId = groupId;
        this.getData();
      });
    },
    created() {
      // 检查URL中是否已经包含打开特定数据和视图的参数
      let params = this.$route.params;

      if (Object.keys(params).length > 0 && params.uid && params.view) {
        this.openDataView(params.uid, params.view);
      }

      this.getData();

      Bus.$on('close-upload-panel', () => {
        this.openUpload = false;
      });

      Bus.$off('upload-success');
      Bus.$on('upload-success', (uid) => {
        this.openUpload = false;
        this.openGeoreference = true;
        this.dataUid = uid;
        // 刷新数据列表
        this.dataList = [];
        this.getData(0, false, this.rangeTime);
      });

      Bus.$off('georeference-cancel');
      Bus.$on('georeference-cancel', () => {
        this.openGeoreference = false;
        // 刷新数据列表
        this.dataList = [];
        this.getData(0, false, this.rangeTime);
      });

      Bus.$off('georeference-success-mydata');
      Bus.$on('georeference-success-mydata', (uid) => {
        this.openGeoreference = false;
        this.dataList = [];
        this.getData(0, false, this.rangeTime);
        return;
      });

      Bus.$off('close');
      Bus.$on('close', () => {
        this.openUpload = false;
      });

      Bus.$off('geofile-upload-success');
      Bus.$on('geofile-upload-success', () => {
        this.dataList = [];
        this.getData(0, false, this.rangeTime);
      });

      Bus.$off('close-data-upload');
      Bus.$on('close-data-upload', () => {
        this.openUpload = false;
      });

    },

    activated() {

      // this.$emit( 'on-view-load' );
    },

    computed: {
      isListView() {
        return !!(this.view === 'list-wrapper');
      },
    },

    directives: {
      focus: {
        componentUpdated: function (el, {
          value
        }) {
          if (value) {
            el.focus();
          }
        }
      }
    },

    methods: {

      open() {

      },

      store(data) {
        this.$emit('data-store', data);
      },

      changeRangeType() {
        if (this.loading || this.isEmpty) return;
        this.view = this.view === 'list-wrapper' ? 'tiling-wrapper' : 'list-wrapper';
      },

      changeSortTime() {
        if (this.loading) return;

        this.sortTime = this.sortTime === 'desc' ? 'asc' : 'desc';
        this.getData(0, false, this.sortTime);
      },

      query() {
        if (this.isLoading) {
          return;
        }
        // if (!this.searchText || this.searchText.trim() === '') {
        //   this.$message.warning('请输入搜索关键字');
        //   return;
        // }
        Bus.$emit('search-confirm', this.searchText.trim());
        this.getData(0, false, this.rangeTime);
      },

      addMore() {
        if (this.hasNext) {
          this.page += 1;
          this.getData(this.page, true, this.rangeTime);
        }
      },

      setCurrentMenu(menu) {
        this.currentMenu = menu;
      },

      /**
       * 根据筛选条件请求数据
       * @param {number} 请求页数
       * @param {boolean} 是否对查询结果进行拼接
       */
      getData(page = 0, concat = false, type = 'desc') {

        this.page = page;

        var allParams = {
          page: page,
          limit: limit,
          category: this.selectedCategory,
          admin: this.selectedAdmin,
          search: this.searchText,
          timeOrder: type
        }

        this.getFilteredDataset(allParams, concat);

      },

      /**
       * 根据筛选参数获取过滤数据
       * @param object params 过滤参数对象
       */
      async getFilteredDataset(params, concat) {

        params = params || {};
        //console.log(params);
        let _params = {
          page: params.page,
          rows: params.limit,
          //rows: params.limit,
          sort: 'regDate',
          order: params.timeOrder.toUpperCase(),
          groupId: this.groupId
        };
        if (params.search != "") {
          _params.name = params.search;
        }

        //console.log(_params);

        this.isLoading = true;

        let url = `${newConfig.api}/${this.queryParams.type}/query/ownertype/${this.queryParams.ownerType}`;
        this.$root.$http.get(url, {
          params: _params
        }).then((response) => {
          // console.log(response);
          let data = response.data.data;
          data.items.forEach((item) => {
            item.uid = item.ghid;
          });
          //console.log(JSON.stringify(data.items));

          this.updateDataList(data, concat);

          //关闭加载界面
          this.$emit('change-loading', {
            add: true,
            key: 'group-data'
          });
        });

      },

      /**
       * 更新数据列表
       * @param array data 数据数组
       */
      updateDataList(data, concat) {
        // console.log(data, concat);

        if (data.items.length === 0) {
          this.$message.warning('未找到相应内容');
          this.isLoading = false;
          this.hasNext = false;
          this.dataList = [];
          return;
        }

        if (!concat) {
          this.dataList = [];
        }

        this.dataList = this.dataList.concat(data.items);
        this.isLoading = false;
        this.hasNext = data.hasNext;

        this.isEmpty = !this.dataList.length;

      },

      preview(data) {
        this.previewData = data;
        this.openPreview = true;
      },

      closePreview() {
        this.previewData = '';
        this.openPreview = false;
      },

      async openDataView(uid, viewType) {

        // 获取数据详情
        let dataInfo = await this.getDataInfo(uid);

        if (!dataInfo) {
          return;
        }

        if (viewTypes.indexOf(viewType) === -1) {
          viewType = 'map';
        }

        let customPreviewData = {
          uid: uid,
          geometryType: dataInfo.geomType,
          extent: dataInfo.extent,
          name: dataInfo.name,
          count: dataInfo.count,
          view: viewType,
          convertEnd: !!dataInfo.geomType,
          isPrivate: false,
          path: '/data/group-data'
        };

        // 打开预览窗口
        this.openPreview = true;
        this.previewData = customPreviewData;

      },

      /**
       * 获取数据详情
       * @param string uid 数据UID
       */
      async getDataInfo(uid) {

        let dataInfo = await publicDataAPI.info(uid);

        if (dataInfo.data.code === 0) {
          return dataInfo.data.data;
        }

        this.$message.error('您请求的数据不存在');

        return null;

      },

      upload() {
        this.openUpload = true;
      },

      // 删除数据
      remove(data, dataName) {

        let uid = data.uid;
        let success = false;

        let promise = this.$confirm(
          `数据删除后不可恢复，确认删除数据“${dataName}”？`,
          '删除', {
            type: 'warning',
            confirmButtonType: 'danger',
            confirmButtonText: '删除',
            // parent: this.$refs.myData,
            beforeClose: async (action, instance, done) => {

              if (action === 'confirm') {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = '删除中...';
                instance.cancelButtonDisabled = true;

                let result = await bookmarkAPI.getStored(uid);
                if (result && result.data.code === 0) {
                  let data = result.data.data;
                  let stored = data.bookmarks;
                  Bus.$emit('clear-bookmark-data', stored);
                }


                let removeResult = await publicDataAPI.remove(uid);
                if (removeResult && removeResult.data.code === 0) {
                  success = true;
                  Bus.$emit('summary-reset');
                  Bus.$emit('group-data-reset');
                  done();
                } else {
                  this.$message.error('删除失败');
                  done();
                  return;
                }

                instance.confirmButtonLoading = false;

              } else {
                done();
              }

            }
          }
        );

        promise.then(async () => {

          if (!success) {
            this.$message.error('删除失败');
            return;
          }
          let dataList = this.dataList;
          let index = dataList.findIndex(item => {
            return item.uid == uid;
          })

          if (index >= 0) {
            dataList.splice(index, 1);
            this.$message.success('删除成功');

            let len = dataList.length;

            if (len === 0 && !this.hasNext) {
              this.isEmpty = true;
              return;
            }

            if (len === 0 && this.hasNext) {
              this.getData(0);
            }
          }

          Bus.$emit('clear-bookmark-count');

        }).catch(() => {
          // this.$message.error('取消')
        })
      },
      handleResSwitch(type, event) {
        let currentTarget = event.currentTarget;
        if (currentTarget.classList.contains('active')) {
          return;
        }
        let list = currentTarget.parentNode.querySelectorAll('li');
        for (let item of list) {
          item.classList.remove('active');
        }
        currentTarget.classList.add('active');
        let params = {
          type: 'resourceReg',
          ownerType: '2'
        };
        if (type == '申请资源') {
          params.type = 'resourceApply';
        }
        this.queryParams = params;

        this.getData();
      }
    }
  }

</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "common";

  @media screen and (max-width: 1200px) {

    .upload-data {

      width: 64px !important;

      >span {
        display: none !important;
      }

      >i {
        display: block !important;
      }
    }

    .search {
      display: none !important;
    }
  }

  .public-data {
    height: 100%;
    width: 100%;
    font-size: 12px;
    position: relative;
    @include box-sizing(border-box);

    .option {

      width: 100%;
      // min-height: 50px;
      // position: relative;
      position: absolute;
      top: 0;
      padding: 18px 0;
      @include box-shadow(0 4px 6px 2px rgba(255, 255, 255, 0.3));

      .option-container {

        overflow: hidden;

        .upload-data {
          height: 30px;
          line-height: 28px;
          width: 90px;
          border-radius: 3px;
          color: $white;
          text-align: center;
          float: left;
          background-color: $primary;
          cursor: pointer;
          margin-right: 16px !important;

          &:hover {
            background-color: $darkPrimary;
            font-weight: 500;
          }

          >i {
            font-size: 18px;
            line-height: 30px;
            font-weight: 500;
            display: none;
          }
        }

        .filter-position {
          float: left;
          padding: 4.5px 0 !important;
        }


        .range {
          display: block;
          float: right;
          width: 160px;
          color: $gray;
          padding: 6px 0;
          cursor: pointer;
          text-align: right;
          @include user-select(none);

          >span {
            line-heigth: 32px;
            height: 32px;
            text-align: center;
            font-size: 14px;
            padding: 0 5px;

            &:hover {
              color: $primary;
            }
          }
        }

        .search {

          float: right;
          width: 210px;
          color: $gray;
          position: relative;

          .input-search {
            width: 210px;
            height: 32px;
            padding: 6px 42px 6px 12px;
            border: 1px solid $bdGray;
            border-radius: 16px;

            &:focus {
              border-color: $info;
            }
          }

          .btn-search {
            width: 32px;
            height: 32px;
            text-align: center;
            line-height: 32px;
            cursor: pointer;
            position: absolute;
            right: 6px;
            top: 0;

            >i {
              font-size: 14px;
            }

            &:hover {
              color: $primary;
            }
          }
        }
      }

    }

    .filter-panel {
      position: absolute;
      top: 56px;
      z-index: 10;

    }

    .category-filter {
      width: 160px;
      float: left;
      outline-style: none;

      .switch-category {
        width: 100%;
        height: 32px;
        padding: 6px 12px;
        border: 1px solid $bdGray;
        border-radius: 16px;
        cursor: pointer;


        >i {
          float: right;
          @include transition(all .5s);
        }

        .open-category {
          @include transform(rotate(180deg) translateY(6%));
        }

        .close-category {
          @include transform(translateY(20%));
        }
      }

      .category-container {
        width: 238px;
        height: 196px;
        padding: 4px;
        border: 1px solid $bdGray;
        border-radius: $bdRadius;
        background-color: $bgWhite;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        margin-top: 4px;
        overflow: hidden;
        position: absolute;
        z-index: 999;

        .category {
          width: 60px;
          text-align: center;
          padding: 2px 4px;
          margin: 4px 8px;
          border: 1px solid $bdGray;
          color: $gray;
          border-radius: $bdRadius;
          float: left;
          cursor: pointer;

          &:hover {
            border: 1px solid darken($bdGray, 10%);
          }
        }

        .active-category {
          border: 1px solid $lightPrimary;

          &:hover {
            border: 1px solid $lightPrimary !important;
          }
        }
      }
    }

    // 数据列表在筛选面板打开时的样式
    .data-list-with-panel-open {
      height: calc(100% - 220px);
    }

    // 数据列表在筛选面板关闭时的样式
    .data-list-with-panel-closed {
      padding-top: 20px;
      height: calc(100% - 40px);
    }

  }

  .spread-enter-active {
    @include animation(spread-in .3s);
  }

  .spread-leave-active {
    @include animation(spread-out .3s);
  }

  @include keyframes(spread-in) {
    0% {
      height: 0px
    }

    100% {
      height: 196px
    }
  }

  @include keyframes(spread-out) {
    0% {
      height: 196px
    }

    100% {
      height: 0px
    }
  }

  .spin {
    display: inline-block;
    font-size: 12px;
    @include animation(icon-spin 2s infinite linear);
  }

  @include keyframes(icon-spin) {
    from {
      @include rotate(0)
    }

    to {
      @include rotate(359)
    }
  }

  .resource-switch {
    position: absolute;
    top: 42px;
  }

  .resource-switch li {
    float: left;
    padding: 0 3px 6px;
    margin-right: 26px;
    font-size: 14px;
  }

  .resource-switch .active {
    border-bottom: 2px solid #5089FF;
    color: #5089FF;
  }

  .resource-switch li:hover {
    cursor: pointer;
  }

</style>
